// AgentSelection.tsx
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Row, Col, Input, Empty, Spin, Tabs } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import styles from "./AgentSelection.module.scss";
import AgentCard from "../../components/AgentCard/AgentCard";
import {
  getAllAgentGroup,
  getAgentsByGroup,
  searchAgents,
} from "../../services/agent";
import { Agent, AgentGroup } from "../../types";

import { useAgentStore } from "../../context";

const { TabPane } = Tabs;

const AgentSelection = () => {
  const [agents, setAgents] = useState<Agent[]>([]);
  const [filteredAgents, setFilteredAgents] = useState<Agent[]>([]);
  const [agentGroups, setAgentGroups] = useState<AgentGroup[]>([]);
  const [searchText, setSearchText] = useState("");
  const [loading, setLoading] = useState(true);
  const [currentGroupId, setCurrentGroupId] = useState<number>(0); // 默认选择第一个分组
  const navigate = useNavigate();

  // 获取所有 Agent 分组
  useEffect(() => {
    const fetchAgentGroups = async () => {
      try {
        setLoading(true);
        const groups = await getAllAgentGroup();
        setAgentGroups(groups);

        // 如果有分组数据，默认选择第一个分组
        if (groups.length > 0) {
          setCurrentGroupId(groups[0].id);
        }
      } catch (error) {
        console.error("获取 Agent 分组失败:", error);
      }
    };

    fetchAgentGroups();
  }, []);

  // 当分组变化时，获取该分组下的 Agents
  useEffect(() => {
    const fetchAgentsByGroup = async () => {
      if (currentGroupId === undefined) return;

      try {
        setLoading(true);
        const agentList = await getAgentsByGroup(currentGroupId);
        setAgents(agentList);
        setFilteredAgents(agentList);
      } catch (error) {
        console.error(`获取分组 ${currentGroupId} 的 Agents 失败:`, error);
      } finally {
        setLoading(false);
      }
    };

    fetchAgentsByGroup();
  }, [currentGroupId]);

  // 处理搜索功能
  useEffect(() => {
    const handleSearch = async () => {
      if (!searchText) {
        // 如果搜索框为空，显示当前分组的所有 agents
        setFilteredAgents(agents);
        return;
      }

      try {
        setLoading(true);
        // 调用搜索 API
        const searchResults = await searchAgents(searchText);
        setFilteredAgents(searchResults);
      } catch (error) {
        console.error("搜索 Agents 失败:", error);
        // 搜索失败时，使用本地过滤作为备选方案
        const filtered = agents.filter(
          (agent) =>
            agent.AIName.toLowerCase().includes(searchText.toLowerCase()) ||
            agent.AIDesc.toLowerCase().includes(searchText.toLowerCase())
        );
        setFilteredAgents(filtered);
      } finally {
        setLoading(false);
      }
    };

    // 使用防抖处理搜索，避免频繁请求
    const debounceTimer = setTimeout(handleSearch, 300);
    return () => clearTimeout(debounceTimer);
  }, [searchText, agents]);

  const setSelectedAgent = useAgentStore((state) => state.setSelectedAgent);

  const handleAgentSelect = (agent: Agent) => {
    setSelectedAgent(agent);

    navigate(`/chat/${agent.ID}`);
  };

  const handleTabChange = (activeKey: string) => {
    setCurrentGroupId(Number(activeKey));
    setSearchText(""); // 切换分组时清空搜索框
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <Input.Search
          placeholder="请输入关键词"
          enterButton={<><SearchOutlined/> 搜索</>} 
          onChange={(e) => setSearchText(e.target.value)}
          value={searchText}
          className={styles.searchInput}
          size="large"
          allowClear
        />
      </div>

      <div className={styles.tabsContainer}>
        <Tabs
          activeKey={currentGroupId.toString()}
          onChange={handleTabChange}
          className={styles.tabs}
        >
          {agentGroups.map((group) => (
            <TabPane tab={group.name} key={group.id.toString()} />
          ))}
        </Tabs>
      </div>

      {loading ? (
        <div className={styles.loading}>
          <Spin size="large" />
        </div>
      ) : filteredAgents.length > 0 ? (
        <Row gutter={[30, 30]} className={styles.agentGrid}>
          {filteredAgents.map((agent) => (
            <Col xs={16} sm={16} md={16} lg={8} key={agent.ID}>
              <AgentCard
                agent={agent}
                onSelect={() => handleAgentSelect(agent)}
              />
            </Col>
          ))}
        </Row>
      ) : (
        <Empty description="没有找到匹配的 AI 助手" />
      )}
    </div>
  );
};

export default AgentSelection;
